﻿using System;
using System.Collections.Generic;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using ZealandIT.MsBuildTasks.Common;

namespace ZealandIT.MsBuildTasks.IO
{
    /// <summary>
    /// This class appends content to an existing file. If username, password and domain
    /// are specified, it will impersonate on that user's behalf while performing the append.
    /// This will allow this task to work across UNC file paths and shares.
    /// </summary>
    public class AppendToFile : Task
    {
        private string _file;
        private string _contentToAppend;
        private string _username;
        private string _password;
        private string _domain;

        /// <summary>
        /// File to append to.
        /// </summary>
        [Required]
        public string File
        {
            get { return _file; }
            set { _file = value; }
        }

        /// <summary>
        /// Content to append to <see cref="File"/>.
        /// </summary>
        [Required]
        public string ContentToAppend
        {
            get { return _contentToAppend; }
            set { _contentToAppend = value; }
        }

        /// <summary>
        /// Username to be used to impersonate - if <see cref="UseImpersonation"/> is set to true.
        /// </summary>
        public string Username
        {
            get { return _username; }
            set { _username = value; }
        }

        /// <summary>
        /// Password associated with <see cref="Username"/>.
        /// </summary>
        public string Password
        {
            get { return _password; }
            set { _password = value; }
        }

        /// <summary>
        /// Domain for the user.
        /// </summary>
        public string Domain
        {
            get { return _domain; }
            set { _domain = value; }
        }

        private bool UseImpersonation
        {
            get
            { 
                return (_username != null && _password != null); 
            }
        }

        /// <summary>
        /// Main MSBuild Execute task.
        /// </summary>
        /// <returns>True if successful, else false.</returns>
        public override bool Execute()
        {
            if (!System.IO.File.Exists(_file))
            {
                Log.LogError("File {0} does not exist.", _file);
                return false;
            }
            try
            {
                IoHelper.AppendToFile(_file, _contentToAppend, _username, _password, _domain);
            }
            catch (Exception ex)
            {
                Log.LogErrorFromException(ex);
                return false;
            }
            return true;
        }
    }
}
